<template>
  <div>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="个人信息" name="first">
        <el-form>
          <el-form-item label="账号">
            {{ userInfo.userAccount || '-' }}
          </el-form-item>
          <el-form-item label="手机号">
            {{ userInfo.phone || '-' }}
          </el-form-item>
          <el-form-item label="UID ">
            {{ userInfo.id }}
          </el-form-item>
          <el-form-item label="会员">
            {{ userInfo.isMember == '1' ? '是' : '否' }}
          </el-form-item>
          <el-form-item label="会员有效期">
            {{ userInfo.yxqEnd || '-' }}
          </el-form-item>
          <el-form-item label="余额">
            {{ userInfo.money || '0' }}
          </el-form-item>
        </el-form>
        <el-button color="#202123" icon="User" @click="handleCommand">退出登录</el-button>
      </el-tab-pane>
      <el-tab-pane label="服务订阅" name="second">
        <!-- <el-row :gutter="10">
                <el-col :span="6">
                    <el-card>
                        <div class="payTime">月付</div>
                        <div class="pay-money">￥9.9</div>
                        <el-button type="primary">立即订阅</el-button>
                    </el-card>
                </el-col>
                <el-col :span="6">
                    <el-card>
                        <div class="payTime">季付</div>
                        <div class="pay-money">￥9.9</div>
                        <el-button type="primary">立即订阅</el-button>
                    </el-card>
                </el-col>
                <el-col :span="6">
                    <el-card>
                        <div class="payTime">年付</div>
                        <div class="pay-money">￥9.9</div>
                        <el-button type="primary">立即订阅</el-button>
                    </el-card>
                </el-col>
            </el-row> -->
        <div class="cardBox">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" v-for="item in goods" :key="item.id">
              <div class="card" @click="showBuy(item)">
                <div class="payTime">{{ item.title }}</div>
                <div class="pay-money">￥{{ item.money }}</div>
                <div class="remark">{{ item.remark }}</div>
                <el-button class="cardBtn" type="primary">立即订阅</el-button>
              </div>
            </el-col>
          </el-row>

          <!-- <div class="card">
                    <div class="payTime">季付</div>
                    <div class="pay-money">￥80</div>
                    <el-button class="cardBtn" type="primary">立即订阅</el-button>
                </div>
                <div class="card">
                    <div class="payTime">年付</div>
                    <div class="pay-money">￥300</div>
                    <el-button class="cardBtn" type="primary">立即订阅</el-button>
                </div> -->
        </div>
      </el-tab-pane>
      <el-tab-pane label="密码修改" name="third">
        <el-form :model="form" :rules="rules" class="password-wrap">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone"></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input v-model="form.code"></el-input>
            <el-button :disabled="countdown > 0" @click="sendCaptcha">{{ countdown > 0 ? `${countdown}s` :
              '发送验证码' }}</el-button>
          </el-form-item>
          <el-form-item label="密码" prop="newPassword">
            <el-input v-model="form.newPassword" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updatePassword">保存</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="余额充值" name="fourth">
        <el-form :model="balanceForm" label-width="80px" class="demo-ruleForm password-wrap">
          <el-form-item label="充值金额" :rules="[
              { required: true, message: '金额是必填的' },
              { type: 'number', message: '金额是数字类型' },
            ]" prop="money">
            <el-input v-model.number="balanceForm.money" placeholder="请输入充值金额"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="showBuy('充值')">立即充值</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <el-dialog class="BuyPay" v-model="dialogVisible" :title="dialogTitle" width="720px" top="9vh"
      :before-close="handleClose" :close-on-click-modal="false">
      <div class="form-box" v-loading="loading">
        <el-form class="form-content" label-width="80" label-position="left">
          <el-form-item label="套餐" v-show="dialogTitle === '订阅'">
            {{ formData.name }}
          </el-form-item>
          <el-form-item label="支付金额">
            <span style="color: #FF7800;font-size: 18px;">￥ {{ formData.money }}</span>
          </el-form-item>
          <el-form-item label="支付方式">
            <el-radio-group v-model="formData.pay_type">
              <el-radio label="1" size="large" border>
                微信
              </el-radio>
              <el-radio label="2" size="large" border>
                支付宝
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <el-dialog v-model="innerVisible" width="720px" top="9vh" :title="dialogTitle" append-to-body
          :close-on-click-modal="false" @close="goPrevious">
          <div class="payCode-wrap">
            <div style="margin-top: 20px;" v-show="formData.pay_type == '1'">支付金额￥{{ formData.money }}</div>
            <div class="pay-code" v-show="formData.pay_type == '1'">
              <img :src="payCode" alt="">
            </div>
            <div v-show="formData.pay_type == '2'">
              <iframe :srcdoc="aliForm" frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no"
                width="700" height="620" style="overflow: auto"></iframe>
            </div>
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button size="large" @click="goPrevious">上一步</el-button>
              <el-button size="large" type="primary" @click="aleadyBuyPay" :loading="payCodeLoad">已完成支付</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="large" @click="handleClose">取消</el-button>
          <el-button size="large" type="primary" @click="submitForm">支付</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 充值余额弹窗 -->
    <!-- <el-dialog v-model="isShowDialog">
      <div class="payCode-wrap">
        <div style="margin-top: 20px;">支付金额￥{{ balanceForm.money }}</div>
        <div class="pay-code">
          <img :src="payCode" alt="">
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="large" @click="isShowDialog = false">取消</el-button>
          <el-button size="large" type="primary" @click="aleadyBuyPay" :loading="payCodeLoad">已完成支付</el-button>
        </span>
      </template>
    </el-dialog> -->
  </div>
</template>
<script setup lang='ts'>
import type { TabsPaneContext } from 'element-plus'
import orderApi from '@/api/order'
import { setToken } from '@/utils/index'
import loginApi from '@/api/login'
import { removeToken } from '@/utils'
import {
  ElMessageBox, ElForm,
  ElFormItem,
  ElInput,
  ElButton
} from 'element-plus'
import QRCode from 'qrcode'
import { defineEmits, ref, reactive } from 'vue'
import request from "@/utils/request";
// 设置事件名
const emit = defineEmits(['showLogin'])
const router = useRouter()
let checkPayTimer: any = null, timeoutTimer: any = null

const activeName = ref('first')

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}

const goods = ref([])
const form = ref({
  phone: '',
  code: '',
  newPassword: '',
})

const balanceForm = reactive({
  money: ''
})

const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}
const countdown = ref(0)
const dialogTitle = ref('订阅')

const sendCaptcha = () => {
  loginApi.sendCode(form.value.phone).then((res: any) => {
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value -= 1
      if (countdown.value === 0) {
        clearInterval(timer)
      }
    }, 1000)
  })
}

const updatePassword = () => {
  loginApi.updatePassword(form.value).then((res: any) => {
    ElMessage.success("修改成功")
  })
}
orderApi.allGood().then((res: any) => {
  goods.value = res
})
const userInfo = ref<any>('')
// orderApi.getUserInfo().then((res:any)=>{    
//     userInfo.value = res
// })
onMounted(() => {
  loginApi.getLoginUserInfo().then((res: any) => {
    console.log(res)
    userInfo.value = res
  })

});

// 退出登录
const handleCommand = () => {
  ElMessageBox.confirm('确定退出登录?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    closeOnClickModal: false
  })
    .then(() => {
      loginApi.loginout()
      setTimeout(() => {
        removeToken()
        router.push({
          path: '/home'
        })
        emit('showLogin')
        location.reload()
      }, 300)
    })
    .catch(() => {
      return true
    })
}


// 取消
const handleClose = () => {
  if (loading.value) {
    return false
  }
  clearAllTimer()
  dialogVisible.value = false
}
const loading = ref(false)
const dialogVisible = ref(false)
const innerVisible = ref(false)
const formData = reactive({
  id: '',
  pay_type: '1',
  money: "100",
  name: '',
  orderId: ''
})


function showBuy(mes) {
  if (mes === '充值') {
    if ((balanceForm.money) as any <= 0) {
      ElMessage.error('充值金额必须大于0')
      return
    }

    dialogTitle.value = mes
    formData.name = mes
    formData.money = balanceForm.money
    dialogVisible.value = true
    return;
  } else {
    dialogTitle.value = '订阅'
  }
  console.log(mes)
  formData.id = mes.id
  formData.money = mes.money
  formData.name = mes.title
  dialogVisible.value = true
  // document.cookie= 'satoken=cb3b983c-4d21-49e2-8f67-d79b499bf7dc'
}

// 确定
const payCodeLoad = ref(false)
const payCode = ref('')
const aliForm = ref('')
const submitForm = async () => {
  innerVisible.value = true
  if (loading.value) {
    return
  }

  let data = null
  if (formData.name === '充值') {
    data = await orderApi.createBalanceOrder({
      price: formData.money,
      paytype: formData.pay_type,
      name: formData.name
    })
  } else {
    data = await orderApi.createOrder({
      goodId: formData.id,
      paytype: formData.pay_type
    })
  }
  if (formData.pay_type == '1') {
    const wxData: any = await orderApi.wxpay(data.id)
    formData.orderId = wxData.orderId
    console.log(wxData)
    nextTick(() => {
      QRCode.toDataURL(wxData.codeUrl).then(res => {
        payCode.value = res
        checkPayTimer = setInterval(checkOrder, 5000)
        timeoutTimer = setTimeout(() => {
          clearInterval(checkPayTimer)
        }, 120000)
      })
    })
  }
  else {
    const alipayData: any = await orderApi.alipay(data.id)
    formData.orderId = data.id
    console.log(alipayData, 111)
    aliForm.value = alipayData.body
    checkPayTimer = setInterval(checkOrder, 5000)
    timeoutTimer = setTimeout(() => {
      clearInterval(checkPayTimer)
    }, 120000)
    // nextTick(()=>{
    //     QRCode.toDataURL(alipayData.codeUrl).then(res => {
    //         payCode.value = res
    //         checkPayTimer = setInterval(checkOrder,5000)
    //         timeoutTimer = setTimeout(()=>{ 
    //             clearInterval(checkPayTimer) 
    //         },120000)
    //     }) 
    // })
  }
}
//检查支付
async function checkOrder() {
  if (formData.pay_type === '1') {
    const retData: any = await orderApi.searchOrder(formData.orderId)
    if (retData == '支付成功') {
      payCodeLoad.value = false
      ElMessage.success('支付成功')
      clearAllTimer()
      setTimeout(() => { window.location.reload() }, 1000)
    }
  } else {
    const retData: any = await orderApi.searchAliOrder(formData.orderId)
    console.log(retData, 'ali')
    if (retData.code == '10000') {
      payCodeLoad.value = false
      ElMessage.success('支付成功')
      setTimeout(() => {
        clearAllTimer()
        window.location.reload()
      }, 3000)
    }
  }
}

//上一步
function goPrevious() {
  clearAllTimer()
  innerVisible.value = false
  dialogVisible.value = true
}
//清空定时器
function clearAllTimer() {
  clearInterval(checkPayTimer)
  clearTimeout(timeoutTimer)
  // showTimeout.value = false
}
//已完成支付点击
function aleadyBuyPay() {
  payCodeLoad.value = true
  checkOrder()
  setTimeout(() => {
    window.location.reload()
  }, 3000)
}
</script>
<style lang="scss" scoped>
  ::v-deep .el-form-item__label {
    color: var(--main-font-color) !important;
    transition-property: all;
    transition-duration: 0.6s;
  }

  ::v-deep .el-form-item__content {
    color: var(--main-font-color) !important;
    transition-property: all;
    transition-duration: 0.6s;
  }

  ::v-deep .el-tabs__item {
    color: var(--main-font-color) !important;
    transition-property: all;
    transition-duration: 0.6s;
  }

  ::v-deep .el-input__wrapper {
    background-color: var(--main-shallowbg-color) !important;
    border: 1px solid var(--main-bg-color) !important;
    transition-property: all;
    transition-duration: 0.6s;
  }

  ::v-deep .el-input__inner {
    color: var(--main-font-color) !important;
    transition-property: all;
    transition-duration: 0.6s;
  }

  .cardBox {

    // display: flex;
    // justify-content: flex-start;
    .card {
      padding: 15px;
      background-color: var(--main-bg-color);
      transition-property: all;
      transition-duration: 0.6s;
      margin: 10px 10px 0 0;
      // width: 20%;
      border: 1px solid var(--main-bg-color);
      color: var(--main-font-color);
      border-radius: 5px;
      box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);

      .cardBtn {
        width: 68px;
        font-size: 10px;
        transition-property: all;
        transition-duration: 0.6s;
        background-color: var(--main-elbtn-color) !important;
        border: 1px solid var(--main-elbtn-color) !important;
      }
    }
  }

  .password-wrap {
    max-width: 400px;
  }

  .payTime {
    margin-bottom: 10px;
    font-size: 20px;
    font-weight: 600;
  }

  .pay-money {
    margin-bottom: 10px;
    font-size: 20px;
    font-weight: 600;
  }

  .remark {
    margin: 12px 0;
    font-size: 14px;
    color: var(--main-font-color);
    transition-property: all;
    transition-duration: 0.6s;
  }

  @media screen and (min-width: 600px) {
    .card {
      padding: 15px;
      margin: 10px 10px 0 0;

      // width: 20%;
      .cardBtn {
        width: 100px !important;
        font-size: 14px !important;
      }
    }
  }

  .payCode-wrap {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .pay-num {
      margin-top: 10px;
      color: #1E4DFF;
      font-size: 26px;
      font-weight: 600;
    }
  }

  .pay-code {
    position: relative;
    width: 200px;
    height: 200px;
    font-size: 40px;

    .el-icon {
      font-size: 50px;
      color: #fff;
    }

    img {
      width: 100%;
    }

    .timeout-wrap {
      z-index: 100;
      position: absolute;
      top: 10px;
      left: 10px;
      right: 10px;
      bottom: 10px;
      background-color: rgb(122, 122, 122, 0.4);
      ;
      display: flex;
      justify-content: center;
      align-items: center;
      backdrop-filter: blur(5px);
      cursor: pointer;

      .el-icon {
        font-size: 50px;
        color: #fff;
      }
    }
  }

  .form-content {
    .el-form-item__label {
      font-size: 14px;
    }
  }
</style>